<?php

namespace app\common\services\weixin;

use app\common\services\BaseServices;
use app\common\services\HttpClient;
use app\common\services\StaticServices;
use app\models\OauthAccessToken;

class RequestService extends BaseServices
{
    private static $appid = '';
    private static $app_secret = '';
    private static $token = '';
    private static $url = 'https://api.weixin.qq.com/cgi-bin/';

    public static function getAccessToken($appid, $app_secret)
    {
        $date_now = time();
        $access_token_info = OauthAccessToken::find()->where(['>', 'expired_time', $date_now])->limit(1)->one();
        if ($access_token_info) {
            return $access_token_info;
        }
        //调用接口获取aceess_token
        $path = 'token?grant_type=client_credential&appid=' . $appid . '&secret=' . $app_secret;
        $result_info = self::send($path);
        $js = self::chk_jsapi_ticket($result_info['access_token']);
        if (!$result_info) {
            return self::_err(self::getErrMsg());
        }
        $access_token_info = new OauthAccessToken();
        $access_token_info->access_token = $result_info['access_token'];
        $access_token_info->jsapi_ticket = $js->ticket;
        $access_token_info->expired_time = time() + 7000;
        $access_token_info->create_time = $date_now;
        $access_token_info->save(0);

        return $access_token_info;
    }

    public static function chk_jsapi_ticket($ACCESS_TOKEN = '')
    {
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$ACCESS_TOKEN}&type=jsapi";
        $chk = json_decode(self::GETPost($url));

        return $chk;
    }

    public static function jsapi_ticket_config($url, $configs = '', $appid, $app_secret)
    {
        if ($ACCESSINFOS = self::getAccessToken($appid, $app_secret)) {
            $weixinAppid = $appid;
            $time = time();
            $noncestr = StaticServices::getRandChar(10);
            $key = "jsapi_ticket={$ACCESSINFOS['jsapi_ticket']}&noncestr={$noncestr}&timestamp={$time}&url={$url}";
            $key = sha1($key);
            $configsStr = '';
            if ($configs) {
                foreach ($configs as $k => $v) {
                    $configs[$k] = "'" . $v . "'";
                }
                $configsStr = implode(',', $configs);
            } else {
                $configsStr = "'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'";
            }

            return <<<EOB
wx.config({
     debug: false,
     appId: '$weixinAppid',
     timestamp:$time,
     nonceStr: '$noncestr',
     signature:'$key',
     jsApiList: [$configsStr]
});
EOB;
            // return '//jsapi ticket失败：[' . $weixin->errcode . ']' . $weixin->errmsg . "[" . $access_token . "]";
        } else {
            return '//未登录1';
        }
    }

    public static function send($path, $data = [], $method = 'GET')
    {
        $request_url = self::$url . $path;
        if ($method == 'POST') {
            $result = HttpClient::post($request_url, $data);
        } else {
            $result = HttpClient::get($request_url, []);
        }
        $result = @json_decode($result, true);
        if (!$result || isset($result['errcode']) && $result['errcode']) {
            return self::_err($result['errmsg']);
        }

        return $result;
    }

    public static function setConfig($appid, $app_secret, $token)
    {
        self::$appid = $appid;
        self::$app_secret = $app_secret;
        self::$token = $token;
    }

    /**
     * @return string
     */
    public static function getAppid()
    {
        return self::$appid;
    }

    /**
     * @return string
     */
    public static function getAppSecret()
    {
        return self::$app_secret;
    }

    /**
     * @return string
     */
    public static function getToken()
    {
        return self::$token;
    }

    public static function GETPost($url)
    {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            if (!$result = curl_exec($ch)) {
                return curl_error($ch);
            }
//            $this->httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            return $result;
        } catch (Exception $ex) {
            return false;
        }
    }

    public static function GetUrl($Status = false)
    {
        if ($Status) {
            if (!empty($_SERVER['REQUEST_URI'])) {
                $scriptName = $_SERVER['REQUEST_URI'];
                $nowurl = $scriptName;
            } else {
                $scriptName = $_SERVER['PHP_SELF'];
                if (empty($_SERVER['QUERY_STRING'])) {
                    $nowurl = $scriptName;
                } else {
                    $nowurl = $scriptName . '?' . $_SERVER['QUERY_STRING'];
                }
            }
            $domain = 'http://' . $_SERVER['HTTP_HOST'];
            return $domain . $nowurl;
        } else {
            $url_this = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
            return $url_this;
        }
    }
}
